package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class EchoHandler implements Handler {
    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response,true, StandardCharsets.UTF_8);
        // 获取请求中的所有参数
        Map<String, String> params = request.getAllParams();

        // 构建响应内容
        StringBuilder contentBuilder = new StringBuilder();
        contentBuilder.append("<html><head><meta charset=\"UTF-8\"><title>Echo Response</title></head><body>");
        contentBuilder.append("<h1>Echo Server Response</h1>");
        contentBuilder.append("<h2>Request Details:</h2>");
        contentBuilder.append("<p>Method: ").append(request.getMethod()).append("</p>");

        // TODO: [222024321072057/王文薏] 根据接收到的参数Map构建HTML列表，回显给客户端
        // 处理参数回显逻辑：如果有参数则用<ul>列表展示，无参数则提示
        if (params.isEmpty()) {
            contentBuilder.append("<h2>No Parameters Received.</h2>");
        } else {
            contentBuilder.append("<h2>Received Parameters:</h2>");
            contentBuilder.append("<ul>");
            // 遍历参数Map，将每个键值对以<li>标签形式添加到列表
            for (Map.Entry<String, String> entry : params.entrySet()) {
                // 转义特殊字符（如&、<、>等），防止XSS攻击和HTML格式错乱
                String key = escapeHtml(entry.getKey());
                String value = escapeHtml(entry.getValue());
                contentBuilder.append("<li><strong>").append(key)
                              .append("</strong>: ").append(value).append("</li>");
            }
            contentBuilder.append("</ul>");
        }

        String content = contentBuilder.toString();

        // TODO: [222024321072057/王文薏] 构造完整的 HTTP 响应头
        // 发送HTTP响应状态行
        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type: text/html; charset=UTF-8");
        writer.println("Content-Length: " + content.getBytes(StandardCharsets.UTF_8).length);
        writer.println("Connection: close");
        writer.println();

        writer.println(content);
        writer.flush();
    }

    /**
     * 转义HTML特殊字符，防止XSS攻击和格式错误
     * @param input 原始字符串
     * @return 转义后的字符串
     */
    private String escapeHtml(String input) {
        if (input == null) {
            return "";
        }
        return input.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }
}
